/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_pwm.h"

#define LED_INTERVAL_TIME_US 15000
#define LED_TASK_STACK_SIZE 1024
#define LED_TASK_PRIO 25

static void *LedLightTask(const char *arg)
{
    (void)arg;

    printf("-----entry pwm demo -----\r\n");

    IoTGpioInit(IOT_GPIO_IO_GPIO_9);
    IoTIoSetFunc(IOT_GPIO_IO_GPIO_9, IOT_IO_FUNC_GPIO_9_PWM0_OUT);
    IoTGpioSetDir(IOT_GPIO_IO_GPIO_9, IOT_GPIO_DIR_OUT);

    IoTPwmInit(IOT_PWM_PORT_PWM0);

    unsigned short duty = 0;
    unsigned int freq = 15000;
    static char plus_status = 0;

    while (1)
    {
        if (duty >= 99)
        {
            plus_status = 0;
        }
        else if (duty <= 0)
        {
            plus_status = 1;
        }

        if (plus_status)
        {
            duty++;
        }
        else
        {
            duty--;
        }

        usleep(LED_INTERVAL_TIME_US);
        IoTPwmStart(IOT_PWM_PORT_PWM0, duty, freq);
    }

    return NULL;
}

static void IotGpioBreathingLedLamp(void)
{
    osThreadAttr_t attr;
    attr.name = "LedLightTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)LedLightTask, NULL, &attr) == NULL)
    {
        printf("[Talkweb Niobe] Falied to create LedLightTask!\n");
    }
    return;
}

APP_FEATURE_INIT(IotGpioBreathingLedLamp);
